<?php

namespace Users\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\Authentication\AuthenticationService;
use Zend\Authentication\Adapter\DbTable as DbTableAuthAdapter;
use Zend\View\Model\ViewModel;
use Zend\Validator\File\NotExists;
use Users\Form\UploadImageForm;
//use Users\Form\UploadImageFilter;
use Users\Model\UploadImage;

use WebinoImageThumb;
//use ZendGData;
//use ZendGData\HttpClient;
//use ZendGData\ClientLogin;


/**
 * MediaManagerController
 *
 * @author
 *
 * @version
 *
 */
class MediamanagerController extends AbstractActionController {
	/**
	 * The default action - show the home page
	 */
	protected $LastUploadFiles;
	protected $filename;
	protected  $authservice;
	
	const GOOGLE_USER_ID='bupiotr@wp.pl';
	const GOOGLE_PASSWORD='aA33Zz12';
	
	public function indexAction() {
		// TODO Auto-generated MediaManagerController::indexAction() default action
		$uploadImageTable = $this->getServiceLocator()->get('UploadImagTable');	
		$userTable = $this->getServiceLocator()->get('Users\Model\UserTable');
		// Get User Info from Session
		$userEmail = $this->getAuthService()->getStorage()->read();
		$user = $userTable->getUserByEmail($userEmail);
		//throw new \Zend\File\Transfer\Exception\InvalidArgumentException('b��d '.var_dump($uploadImageTable->getUploadsByUserId($user->id)));
		//throw new \Zend\File\Transfer\Exception\InvalidArgumentException('b��d '.var_dump($this->basePath("/data/uploads_images/tn_tlo_napi_szyb_8.jpg")));
		$viewModel = new ViewModel( array('myUploads' => $uploadImageTable->getUploadsByUserId($user->id),));
		//throw new \Zend\File\Transfer\Exception\InvalidArgumentException('b��d '.var_dump($viewModel));
		return  $viewModel;
	}
	
	public function getAuthService()
	{
		if (! $this->authservice) {
			$dbAdapter = $this->getServiceLocator()->get('Zend\Db\Adapter\Adapter');
			$dbTableAuthAdapter = new DbTableAuthAdapter($dbAdapter,'user','email','password', 'MD5(?)');
			$authService = new AuthenticationService();
			$authService->setAdapter($dbTableAuthAdapter);
			$this->authservice = $authService;
		}
		return $this->authservice;
	}
	
	//public function addAction()
	//{
		//$uploadTable = $this->getServiceLocator()->get('UploadImagTable');
		//throw new \Zend\File\Transfer\Exception\InvalidArgumentException('b��d'.var_dump($Names));
	//	$form = new UploadImageForm();
	//	$viewModel = new ViewModel(array('form' =>$form,));
	//	return $viewModel;
	//}
	
	public function addAction() //was processuploadAction()
	{
		$form = new UploadImageForm();                          
		$request=$this->request;
		//*****************************************
		//$inputFilter = new UploadImageFilter();
		//$form->setInputFilter($inputFilter);
		//*****************************************
		//$post = array_merge_recursive(
		//		$request->getPost()->toArray(),
		//		$request->getFiles()->toArray()
		//);
		//******************************************
		if ($request->isPost()){
			$uploadFile = $this->params()->fromFiles('filename');
			$form->setData($request->getPost());
				
			if ($form->isValid()) {
				//Fetch Configuration from Module Config
				$uploadPath = $this->getFileUploadLocation();
				throw new \Zend\File\Transfer\Exception\InvalidArgumentException(' jest '.var_dump($uploadPath));
				// Save Uploaded file
				$adapter = new \Zend\File\Transfer\Adapter\Http();
				$adapter->setDestination($uploadPath);
				//$adapter->setDestination('/home/bupiotr/.apps/http/__default__/0/Project_01/1.0.0/data/uploads_images');
				//$adapter->addValidator('Exists',false);
				//$adapter->addValidator('File/Size',true,array('min'=>20,'max'=>2000));
				// checking if file already exist
				$uploadImagesTable = $this->getServiceLocator()->get('UploadImagTable');
				$filenameapp = $uploadFile['name'];
				$this->filename = $filenameapp;
				$rowfile = $uploadImagesTable->getUploadfilename($filenameapp);
				//if ($rowfile == NULL) {
				//****************************************************************
				//throw new \Zend\File\Transfer\Exception\InvalidArgumentException(' jest '.var_dump($this->request->getPost()->get('override')));
				if ($this->request->getPost()->get('override')=='not_override')
				{
					//$exists = new NotExists('/home/bupiotr/.apps/http/__default__/0/Zf_2downloads/1.0.0/data/uploads_images');
					$exists = new NotExists('$uploadPath');
					$adapter->addValidators(array($exists),$uploadFile['name']);
				}
				//throw new \Zend\File\Transfer\Exception\InvalidArgumentException(' jest '.var_dump($adapter->isValid()));
				//***************************************************************
						if (!$adapter->isValid()){
							$dataError = $adapter->getMessages();
							$error = array();
							foreach($dataError as $key=>$row)
							{
								$error[] = $row;
							}
							$form->setMessages(array('filename'=>$error ));
						}
						else {
							if ($adapter->receive($uploadFile['name'])) {
								// File upload sucessfull	
								$userEmail = $this->getAuthService()->getStorage()->read();
								$userTable = $this->getServiceLocator()->get('Users\Model\UserTable');
								$user = $userTable->getUserByEmail($userEmail);
								$exchange_data = array();
								if (!$rowfile == NULL)
								{
									$exchange_data['id'] = $rowfile->id;
								}
								$exchange_data['label'] = $this->request->getPost()->get('label');
								$exchange_data['filename'] = $uploadFile['name'];
								$exchange_data['user_id'] = $user->id;
								$exchange_data['thumbnail'] = $this->generateThumbnail($filenameapp);
								$upload = new UploadImage();
								$upload->exchangeArray($exchange_data);
								$uploadImagesTable->saveUpload($upload);
								return $this->redirect()->toRoute('mediamanager' , array('action' => 'success'));
							}
						}
				
				
				} //end from is valid
				else {
					//$filename = $uploadFile['name'];
					//$this->view->filename = $filename;
					//**************************************************************
					//$viewModelfileis  = new ViewModel(array('adapter'=>$adapter,
					//		                       'label'=>$this->request->getPost()->get('label'),
					//                               'rowfile'=>$rowfile,
					//                               'filenameapp'=>$filenameapp,));
					//$viewModelfileis->setTemplate('users/mediamanager/fileisupploaded');
					//**************************************************************
					//$this->fileisupploadedAction($filenameapp);
					//throw new \Zend\File\Transfer\Exception\InvalidArgumentException(' jest '.var_dump($override));
					//*************************************************************
					
					/*return $this->redirect()->toRoute('mediamanager', array(
							'controller' => 'mediamanager',
							'action' => 'fileisupploaded',
							'id' => $rowfile->id,
					        
					));*/
					
					//return $this->redirect()->toRoute('mediamanager' , array('action' => 'index'));
					//return $viewModelfileis;
				    //}   
			        //} 
					$form->populateValues($request->getPost());
					$viewModel = new ViewModel(array(
							'error' => true,
							'form' => $form,
					));
				    $viewModel->setTemplate('users/mediamanager/add');
				    return $viewModel; 
				
			    }  //end form is invalid
		}
		$viewModel = new ViewModel(array('form' => $form,));
		return $viewModel; //return $this->redirect()->toRoute('mediamanager' , 	array('action' => 'index'));
	}
	
	// file is allready uploaded
	public function fileisupploadedAction()
	{
		//$label = $this->params()->fromRoute('subaction');
		$id = (int) $this->params()->fromRoute('id', 0);
		if (!$id) {
			return $this->redirect()->toRoute('mediamanager');
		}
		$uploadImagesTable = $this->getServiceLocator()->get('UploadImagTable');
		$rowfile = $uploadImagesTable->getUpload($id);
		$filenameapp = $rowfile->filename;
		//$uploadFile = $this->uploadFiles;
		//$filenameapp = $uploadFile['name'];
		$request = $this->getRequest();
		if ($request->isPost()) {
			$del = $request->getPost('del', 'No');
			//throw new \Zend\File\Transfer\Exception\InvalidArgumentException(var_dump($del));
			if ($del == 'Yes') {
				 $adapter = new \Zend\File\Transfer\Adapter\Http();
				 $adapter->setDestination('/home/bupiotr/.apps/http/__default__/0/Zf_2downloads/1.0.0/data/uploads_images');
				 //$adapter->isValid($rowfile->filename);
				 throw new \Zend\File\Transfer\Exception\InvalidArgumentException(var_dump($adapter->isValid($rowfile->filename)));
					 if ($adapter->receive($rowfile->filename)) {
					 	return $this->redirect()->toRoute('mediamanager' ,array('action' => 'success'));
					 }
					 else {
					 	return $this->redirect()->toRoute('mediamanager' ,array('action' => 'fail'));
					 }
				 //throw new \Zend\File\Transfer\Exception\InvalidArgumentException(var_dump($label));				 
				
			}
			else {
				return $this->redirect()->toRoute('mediamanager' , 	array('action' => 'add'));
			}
		}
		//$this->view->filename=$this->filename;
		//$filename = $this->params()->fromRoute('file');
		//$uploadImagesTable = $this->getServiceLocator()->get('UploadImagTable');
		//$image = $uploadImagesTable->getUpload($id);
		$viewModel = new ViewModel(array('id'=>$id,'filenameapp'=>$filenameapp,));
		return $viewModel;
	}
	
	
	public function successAction()
	{
		$request=$this->request;
		if ($request->isPost())
		{
			return $this->redirect()->toRoute(mediamanager , array(
				'controller' => 'mediamanager',
				'action' => 'index',
		));
		}
		return new ViewModel();
	}
	
	public function failAction()
	{
		//$viewModel = new ViewModel();
		return $this->redirect()->toRoute(mediamanager , array(
				'controller' => 'mediamanager',
				'action' => 'index',
		));	
	}
	
	public function deleteAction()
	{
		$id = (int) $this->params()->fromRoute('id', 0);
		if (!$id) { 
			return $this->redirect()->toRoute('mediamanager');
		}
		$request = $this->getRequest(); 
		
		//throw new \Zend\File\Transfer\Exception\InvalidArgumentException('jest');
		if ($request->isPost()) {
			$del = $request->getPost('del', 'No');
			//throw new \Zend\File\Transfer\Exception\InvalidArgumentException(var_dump($del));
			if ($del == 'Yes') {
				$id = (int) $request->getPost('id');
				//throw new \Zend\File\Transfer\Exception\InvalidArgumentException(var_dump($id));
				$uploadTable = $this->getServiceLocator()->get('UploadImagTable');
				$image = $uploadTable->getUpload($id);
				$uploadTable->deleteUpload($id);
				//do the same with files on server
				$path = '/home/bupiotr/.apps/http/__default__/0/Zf_2downloads/1.0.0/data/uploads_images/';		
				$filename = $path.$image->filename;
				if (file_exists($filename))
				{
					unlink($filename);
				}
				$filename = $path.$image->thumbnail;
				if (file_exists($filename))
				{
					unlink($filename);
				}
			}
			// Redirect to list of uploads
			return $this->redirect()->toRoute('mediamanager');
		}
		
		$uploadImageTable = $this->getServiceLocator()->get('UploadImagTable');
		//$viewModel = new ViewModel(array('MyUpload'=>$uploadImageTable->getUpload($id),));
		return array('id'=> $id,'MyUpload'=>$uploadImageTable->getUpload($id),); //$viewModel; //$this->redirect()->toRoute('mediamanager');
	}
	
	
	public function generateThumbnail($imageFileName)
	{
		//$path = '/home/bupiotr/.apps/http/__default__/0/Zf_2downloads/1.0.0/data/uploads_images'; //$this->getFileUploadLocation();
		$path = realpath(__DIR__ . '/../../../../../data/uploads_images'); //$this->getFileUploadLocation();
		$sourceImageFileName = $path . '/' . $imageFileName;
		$thumbnailFileName = 'tn_' . $imageFileName;
		$imageThumb = $this->getServiceLocator()->get('WebinoImageThumb');
		//throw new \Zend\File\Transfer\Exception\InvalidArgumentException('  '.var_dump($imageThumb));
		$thumb = $imageThumb->create(
				$sourceImageFileName,
				$options = array());
		$thumb->resize(75, 75);
		$thumb->save($path . '/' . $thumbnailFileName);
		return $thumbnailFileName;
	}
	
	public function showImageformAction()
	{
		$uploadId = $this->params()->fromRoute('id');
		$uploadTable = $this->getServiceLocator()->get('UploadImagTable');
		$upload = $uploadTable->getUpload($uploadId);
		// ***************code for downloading**********************
		// Fetch Configuration from Module Config
		//$uploadPath = $this->getFileUploadLocation();
		//$uploadPath = '/home/bupiotr/.apps/http/__default__/0/Zf_2downloads/1.0.0/data/uploads_images';
		//if ($this->params()->fromRoute('subaction') == 'thumb')
		//{
		//	$filename = $uploadPath ."/" . $upload->thumbnail;
		//} else {
		//	$filename = $uploadPath ."/" . $upload->filename;
		//}
		//throw new \Zend\File\Transfer\Exception\InvalidArgumentException('  '.print_r($filename));
		//$this->view->layout()->disableLayout(); //dodane
	    //$file = file_get_contents($filename);	
		//$file = readfile($filename);
		//throw new \Zend\File\Transfer\Exception\InvalidArgumentException('  '.var_dump($file));
		// Directly return the Response
		//$response = $this->getEvent()->getResponse();
        //$response->getHeaders()->addHeaders(array(
                  //'Content-Type' => 'application/octet-stream',
        		  //'Content-Type: image/jpeg',
                  //'Content-Disposition' => 'attachment;filename="'.$upload->filename . '"',)); 
		//$response->setContent($file);
		$viewModel = new ViewModel(array('upload' => $upload,));
		return $viewModel; //$response;
	}
	
	public function showImageAction()
	{
		$uploadId = $this->params()->fromRoute('id');
		$uploadTable = $this->getServiceLocator()->get('UploadImagTable');
		$upload = $uploadTable->getUpload($uploadId);
		// Fetch Configuration from Module Config
		//$uploadPath = $this->getFileUploadLocation();
		$uploadPath = '/home/bupiotr/.apps/http/__default__/0/Zf_2downloads/1.0.0/data/uploads_images';
		throw new \Zend\File\Transfer\Exception\InvalidArgumentException('b��d ');
		if ($this->params()->fromRoute('subaction') == 'thumb')
		{
			$filename = $uploadPath ."/" . $upload->thumbnail;
		} else {
			$filename = $uploadPath ."/" . $upload->filename;
		}
		header("Content-Type: image/jpeg");
		readfile($filename);
	}
	
	public function getFileUploadLocation()
	{
		// Fetch Configuration from Module Config
		$config = $this->getServiceLocator()->get('config');
		return $config['module_config']['image_upload_location'];
	}
	
	public function getGooglePhotos()
	{ 
		/*$adapter = new \Zend\Http\Client\Adapter\Curl();
		$adapter->setOptions(array(
				'curloptions' => array(
						CURLOPT_SSL_VERIFYPEER => false,
				)
		));
		$httpClient = new \ZendGData\HttpClient();
		$httpClient->setAdapter($adapter);
		$client = \ZendGData\ClientLogin::getHttpClient(
				self::GOOGLE_USER_ID,
				self::GOOGLE_PASSWORD,
				\ZendGData\Photos::AUTH_SERVICE_NAME,
				$httpClient);
	    $gp = new \ZendGData\Photos($client);
		$userFeed = $gp->getUserFeed( self::GOOGLE_USER_ID );
		foreach ($userFeed as $userEntry) {
			$albumId = $userEntry->getGphotoId()->getText();
			$gAlbums[$albumId]['label'] = $userEntry->getTitle()->getText();
			$query = $gp->newAlbumQuery();
			$query->setUser( self::GOOGLE_USER_ID );
			$query->setAlbumId( $albumId );
			$albumFeed = $gp->getAlbumFeed($query);
			foreach ($albumFeed as $photoEntry) {
				$photoId = $photoEntry->getGphotoId()->getText();
				if ($photoEntry->getMediaGroup()->getContent() != null) {
					$mediaContentArray = $photoEntry->getMediaGroup()->getContent();
					$photoUrl = $mediaContentArray[0]->getUrl();
				}
				if ($photoEntry->getMediaGroup()->getThumbnail() != null)
				{
					$mediaThumbnailArray = $photoEntry->getMediaGroup()->getThumbnail();
					$thumbUrl = $mediaThumbnailArray[0]->getUrl();
				}
				$albumPhoto = array();
				$albumPhoto['id'] = $photoId;
				$albumPhoto['photoUrl'] = $photoUrl;
				$albumPhoto['thumbUrl'] = $thumbUrl;
				$gAlbums[$albumId]['photos'][] =$albumPhoto;
			}
			}
			// Return the consolidated array back to the view for rendering
			return $gAlbums;*/
	}
	
}